/**
 * 
 */
package com.dovgopoly.carlogbook.services.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import com.dovgopoly.carlogbook.services.LoginService;
import com.dovgopoly.carlogbook.services.exceptions.AuthException;
import com.dovgopoly.carlogbook.services.exceptions.LoginRemoteException;

/**
 * @author e.dovgopoliy
 * 
 */
@Service("loginService")
public class LoginServiceImpl implements LoginService {

	private static final Logger log = LoggerFactory.getLogger(LoginServiceImpl.class);

	@Qualifier("userDetailsServiceImpl")
	@Autowired
	UserDetailsService userDetailsService;

	public void login(String username, String password) throws LoginRemoteException {
		try {
			log.info("Logging in...");

			UserDetails userDetails = userDetailsService.loadUserByUsername(username);
			if (userDetails == null) {
				throw new AuthException("User not found!");
			}
			if (!userDetails.getPassword().equals(password)) {
				throw new AuthException("Password is incorrect!");
			}

			Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails,
					userDetails.getPassword(), userDetails.getAuthorities());
			SecurityContextHolder.getContext().setAuthentication(authentication);

		} catch (Throwable e) {
			log.error(e.getMessage(), e);
			throw new LoginRemoteException(e.getMessage(), e);
		}

	}
}
